package 练习11_线程池综合使用案例;

/**
 * @ClassName: UserAccount
 * @Author: AllenSun
 * @Date: 2025/10/23 23:20
 */
public class UserAccount {
    String userName;
    double balance;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public UserAccount(String userName,double balance){
        this.userName = userName;
        this.balance = balance;
    }

    public void receive(double addAmount){
        synchronized (this){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            balance += addAmount;
            System.out.println(Thread.currentThread().getName()+"存入成功，存入金额："+addAmount);
            System.out.println("用户名："+userName+"，转入后余额为："+balance);
        }
    }

    public void transfer(UserAccount target,double drawAmount){
        synchronized (this){
            if(balance >= drawAmount){
                System.out.println(Thread.currentThread().getName()+"取钱成功，取钱金额："+drawAmount);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                balance -= drawAmount;
                System.out.println("用户名："+userName+"，转出后余额为："+balance);
                target.receive(drawAmount);

            }else{
                System.out.println("余额不足！");
            }
        }
    }

    /**
     * 同步方法，用于执行取钱操作
     * @param drawAmount 要取出的金额
     */
    public synchronized void draw(double drawAmount){
    // 检查账户余额是否足够取款
        if(balance >= drawAmount){
        // 打印取款成功信息，包含当前线程名称和取款金额
            System.out.println(Thread.currentThread().getName()+"取钱成功，取钱金额："+drawAmount);
            try {
            // 使线程休眠1秒，模拟取款处理时间
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            // 打印线程中断异常信息
                e.printStackTrace();
            }
        // 更新账户余额，减去取款金额
            balance -= drawAmount;
        // 打印更新后的账户余额
            System.out.println("用户名："+userName+"，转出后余额为："+balance);
        }else{
        // 如果余额不足，打印提示信息
            System.out.println("用户名："+userName+"，余额不足！");
        }
    }


}
